package com.example.myfirstapp;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {

	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
	static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(2);
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/** Called when the user clicks the Send button */
	public void sendMessage(View view) {
		Intent intent = new Intent(this, DisplayMessageActivity.class);
		EditText editText = (EditText) findViewById(R.id.edit_message);
		
			
		    	Thread th = new Thread() {

		            public synchronized void run() {		    	
		            	URL url = null;
		            	InputStream in = null;
		            	
		            		ConnectivityManager cm = (ConnectivityManager)
		            				getSystemService(Context.CONNECTIVITY_SERVICE);
		            		// test for connection
		            		if (cm.getActiveNetworkInfo() != null
		            				&& cm.getActiveNetworkInfo().isAvailable()
		            				&& cm.getActiveNetworkInfo().isConnected()) {
		            			
		            			String html = loadFromNetwork("http://happyhour.eu01.aws.af.cm/promorequests");
		            			
		            			try {
		            				String token = createToken();
									queue.put(token);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
								} catch (IOException e) {
									// TODO Auto-generated catch block
								}		            			
		            		}
		            		
		            		
		            }
		    	};
		    	try {
		    		//String message = editText.getText().toString();
		    		th.start();
					th.join();
					intent.putExtra(EXTRA_MESSAGE, queue.take());
					startActivity(intent);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	
		    	
	}


	
    private String createToken() throws IOException{
        URL url = new URL("http://happyhour.eu01.aws.af.cm/promorequests");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        
        String payload = "{'promoId'='1','businessEstablishmentId': '1','clientId': '1'}";          
        conn.setRequestProperty("Content-Length", String.valueOf(payload.getBytes().length));        
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");

        
        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(payload);
        osw.flush();
        osw.close();        
        Integer responseCode = conn.getResponseCode();
        
        if(responseCode.equals(418)){
        	return "HTTP ERROR 418, TEAPOT, the promotion is complete";
        }
        String responseMessage = conn.getResponseMessage();
        String headerToken = conn.getHeaderField("token");
        return responseMessage.toString();
    	
    }
    
    
    private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }
    
    private String loadFromNetwork(String urlString){
        InputStream stream = null;
        String str ="";
 
        HttpURLConnection conn = null;
        try {
        	
        	URL url = null;
    		url = new URL(urlString);
    		conn = (HttpURLConnection) url.openConnection();
    		conn.setReadTimeout(10000 /* milliseconds */);
    		conn.setConnectTimeout(15000 /* milliseconds */);
    		conn.setRequestMethod("GET");
    		conn.setDoInput(true);
    		
    		conn.setRequestProperty("Content-Type", "application/json");
    		conn.setRequestProperty("Accept", "application/json");
    		
    		// Start the query
    		conn.connect();
    		stream = conn.getInputStream();
        	
        	
        	
            str = readIt(stream, 500);
            
		} catch (MalformedURLException e) {
			str = "MalformedURLException";
			e.printStackTrace();
		} catch (IOException e) {
			str = "IOException";
			e.printStackTrace();
		}
        
        finally {
           if (stream != null) {
               try {
				stream.close();
				conn.disconnect();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            }
        }
        return str;
    }    
}
